﻿
function enableDisableButton() {
    return CountDictionary(SP.ListOperation.Selection.getSelectedItems()) > 0;
}

var web;
var listid;
var listitem = [];
var siteCollection;
var notifyId = '';
var processingCount = 0;


function ApproveItems() {

    notifyId = SP.UI.Notify.addNotification("Processing...", true);

    var ctx = SP.ClientContext.get_current();
    this.siteCollection = ctx.get_site();
    this.web = ctx.get_web();
    this.listid = SP.ListOperation.Selection.getSelectedList();
    var sdlist = this.web.get_lists().getById(listid);
    var items = SP.ListOperation.Selection.getSelectedItems(ctx);
    var selectedItems = items;
    
    ctx.load(this.siteCollection);

    for (var i = 0; i <= items.length - 1; i++) {
        this.listitem.push(sdlist.getItemById(items[i].id));
        ctx.load(this.listitem[i]);
    }

        
    ctx.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
   
}




function onQuerySucceeded(sender, args) {

    
    for (var i = 0; i <= this.listitem.length - 1; i++) {

        var workflowlink = this.listitem[i].get_item('WorkflowLink');
            ApproveTasks(this.listid, GetQueryParam("ID", workflowlink.get_url()), this.listitem[i].get_id(), workflowlink.get_url());
    }

}


function GetQueryParam(key, querystring) {
    var params = querystring.split("?");

    for (var i = 0; i <= params.length - 1; i++) {
        if (params[i].split("=")[0].toLowerCase() == key.toLowerCase())
            return params[i].split("=")[1];
    }

}



function onQueryFailed(sender, args) {
    alert('failed ' + args.toString());
}
 

 

function ApproveTasks(tasklistId, itemId, taskId, item) {
    var soapEnv = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'> \
                         <soap:Body> \
                            <AlterToDo xmlns='http://schemas.microsoft.com/sharepoint/soap/workflow/'> \
                            <item>" + item + "</item> \
                            <todoId>" + taskId + "</todoId> \
                            <todoListId>" + tasklistId +  "</todoListId> \
                            <taskData><my:myFields xmlns:my='http://schemas.microsoft.com/office/infopath/2003/myXSD'><my:TaskStatus>Approved</my:TaskStatus><my:FieldName_Comments>Workflow web service</my:FieldName_Comments><my:FieldName_DelegateTo /><my:FieldName_NewDescription /><my:FieldName_RequestTo /><my:Status>Completed</my:Status><my:PercentComplete>1</my:PercentComplete></my:myFields></taskData> \
                            </AlterToDo> \
                        </soap:Body> \
                    </soap:Envelope>";
    $.ajax({
        url: siteCollection.get_url() + "/_vti_bin/workflow.asmx",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("SOAPAction",
            "http://schemas.microsoft.com/sharepoint/soap/workflow/AlterToDo");
            },
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        success: Function.createDelegate(this, this.processResult),
        error:reportError,
        contentType: "text/xml; charset=\"utf-8\""
    });

}


var processingComplete;
function processResult(xData, status) {
    processingCount++;
    if (processingCount == this.listitem.length) {
        SP.UI.Notify.removeNotification(notifyId);
        notifyId = '';
        SP.UI.Notify.addNotification("Items Approved", false);
        
    }
}

function reportError(xData, status) {
    processingCount++;
    SP.UI.Notify.addNotification("Multi Item Approval failed", true);
}